package meblog.online.server.config;

import com.alibaba.fastjson2.JSONObject;
import com.auth0.jwt.interfaces.DecodedJWT;
import lombok.extern.slf4j.Slf4j;
import meblog.online.server.entity.User;
import meblog.online.server.utils.JwtUtil;
import meblog.online.server.utils.ResultCode;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Component
public class SecurityInterceptor implements HandlerInterceptor {

    /**
     * 解析路由
     * @param request
     * @return
     */
    private String getUrl(HttpServletRequest request) {
        String url = request.getRequestURI();
        return url.substring(request.getContextPath().length());
    }

    private void addUserToContext(DecodedJWT jwt) {
        String data = jwt.getClaim("data").asString();
        User user = JSONObject.parseObject(data, User.class);
        SecurityUserContext.addUserInfo(user);
    }


    @Override
    public boolean preHandle(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Object handler) throws Exception {
        String url = getUrl(request);
        if (url.equals("/login/index")) {
            return true;
        }
        // 获取Header头
        String token = request.getHeader("Authorization");
        if (StringUtils.isEmpty(token)) {
            throw new SystemException(ResultCode.AUTH_NOT_EXIST);
        }
        // 验证token信息
        DecodedJWT jwt = JwtUtil.verifyToken(token);
        // 将用户信息添加到 ThreadLocal
        addUserToContext(jwt);
        return true;
    }

    @Override
    public void afterCompletion(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Object handler, Exception ex) throws Exception {
        log.info("[{}] => 移出用户信息", Thread.currentThread().getName());
        SecurityUserContext.removeUser();
    }
}
